# -*- coding: utf-8 -*-
# @Time    : 2024/10/29 15:48
# @Author  : CHNJX
# @File    : job_service.py
# @Desc    : 任务服务
import time
from typing import Dict, Optional
from flask import current_app
from ..core.jenkins_client import JenkinsClient
from ..core.scheduler import SchedulerService
import logging

logger = logging.Logger('NVR')


class JobService:
    """任务服务类"""

    def __init__(self):
        self.jenkins_client = JenkinsClient()

    def execute_job(self, job_params: Dict, device_name: Optional[str] = None) -> Dict:
        """执行任务"""
        try:
            if device_name:
                # 首先停止该设备的所有运行中的构建
                self.jenkins_client.stop_device_builds(device_name)
                time.sleep(2)  # 给jenkins一些时间来停止构建

            logger.info(f'开始测试设备：{device_name}')
            # 触发新构建
            logger.info(f'job_params--------------: {job_params}')
            print(f'job_params--------------: {job_params}')
            res = self.jenkins_client.trigger_job(job_params, device_name)

            if res['status'] == 'success':
                build_number = res['build_number']
                job_name = current_app.config['JENKINS_JOB_NAME']

                # 等待构建真正开始
                if self.jenkins_client.wait_for_build_to_start(job_name, build_number):
                    logger.info(f'设备 {device_name} 构建 #{build_number} 已成功开始')
                else:
                    logger.error(f'设备 {device_name} 构建 #{build_number} 未能成功开始')
                    return {"status": "error", "error": "构建未能成功开始"}

            return res
        except Exception as e:
            logger.error(f'执行任务时发生错误: {str(e)}')
            return {"status": "error", "error": str(e)}

    def cancel_device_jobs(self, device_name: str) -> Dict:
        """取消设备的所有任务"""

        scheduler_service = SchedulerService()

        success = True
        message = "Jobs canceled successfully"

        # 停止正在运行的构建
        if not self.jenkins_client.stop_device_builds(device_name):
            success = False
            message = "Failed to stop running builds"

        # 取消调度任务
        if not scheduler_service.cancel_device_jobs(device_name):
            success = False
            message = "Failed to cancel scheduled jobs"

        return {
            "status": "success" if success else "error",
            "message": message,
            "device_name": device_name
        }

    def cancel_all_jobs(self) -> Dict:
        """取消所有任务的方法"""
        scheduler_service = SchedulerService()
        success = True
        message = "Jobs canceled successfully"

        # 停止正在运行的构建
        if not self.jenkins_client.stop_all_builds():
            success = False
            message = "停止流水线构建失败"

        # 取消调度任务
        if not scheduler_service.cancel_all():
            success = False
            message = "取消所有监控任务失败"
        return {
            "status": "success" if success else "error",
            "message": message,
        }
